import { App } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import { FilterRouterArr, RouteList } from "/@ts/router/routes";
import { basicRoutes } from "/@ts/router/routes/static";
import { isRelogin } from "/@ts/axios";
import { ElMessage } from "element-plus";
import { useFullLoading } from "../hooks/fullLoading";
import { useLoginStore } from "/@ts/store/modules/login";
import { usePermissionStore } from "/@ts/store/modules/permission";
const { openLoading, closeLoading } = useFullLoading();

export const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_BASE),

  routes: basicRoutes as unknown as RouteRecordRaw[],
});
// console.log('router :>> ', router.getRoutes());
/**
 * 路由拦截 LoginState
 */
const getFilterRouterName = (name: string): boolean => {
  return FilterRouterArr().filter(res=>res).includes(name)
};
router.afterEach((to, from) => {
  closeLoading();
  // 
});
//页面刷新后重新设置权限页面动态路由，防止出现动态路由404问题

router.beforeEach( (to, from, next) => {
  openLoading();
  const loginStore = useLoginStore();
  const permissionStore = usePermissionStore();
  
  if (to.meta && to.meta.title) {

    document.title = import.meta.env.VITE_PROJECT + '-' + to.meta.title as string
  }

  if (import.meta.env.VITE_SERVER == 'false') {
    if (permissionStore.getSidebarRouters.length === 0) {
      permissionStore.GenerateLocalityRoutes()
      .then((accessRoutes: any[]) => {
       accessRoutes.forEach((route: any) => {
       if (!route.path.includes("http")) {
         router.addRoute(route);
       }
     });
     next({ ...to, replace: false });
       })
    }else{
      next();
    }
    return
  }
  loginStore.setIsLogin();
  const isloginPage: boolean =  getFilterRouterName(to.name as string);
  if (loginStore.getIsLogin) {
    if (to.path === "/login") {
      next({ path: "/" });
      closeLoading();
    } else {
      if (loginStore.getRoles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        loginStore
          .GetInfo()
          .then(() => {
            isRelogin.show = false;
            permissionStore
              .GenerateRoutes()
              .then((accessRoutes: any[]) => {
                accessRoutes.forEach((route: any) => {
                  if (!route.path.includes("http")) {
                    router.addRoute(route);
                  }

                });
                next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
              });
          })
          .catch((err) => {
            loginStore.LogOut().then(() => {
              ElMessage.error(err);
              next({ path: "/login" });
            });
          });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (isloginPage) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      closeLoading();
    }
  }

});
/**
 * 挂载到vue实例函数
 * @param app vue实例
 */
export function setupRouter(app: App<Element>) {
  app.use(router);
}

export default router;
